package com.example.wordpress;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.view.MenuItem;

public class MainActivityCtrl 
{
	public static final int REQUEST_AUTHORIZATION = 1;
	public static final int REQUEST_EDITOR = 2;
	public static final int NEW_POST = -1;
	
	private final MainActivityView mainActivityView;
	private final Database database;
	
	private final Blog blog;
	
	public MainActivityCtrl(Blog blog, MainActivityView view, Database db) {
		this.blog = blog;
		mainActivityView = view;
		database = db;
		
		if(isOnline()) {
			/* Si hay acceso a internet, iniciar Login */
			launchWebActivity(Blog.getAuthorizeEndpoint());
		}
		else {
			/* Caso contrario finalizar la actividad */
			
			AlertDialog.Builder builder = new AlertDialog.Builder(mainActivityView.getActivity());
			builder.setTitle("WordPress");
			builder.setMessage("Internet Connection required, sorry...");
			
			builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			
			    public void onClick(DialogInterface dialog, int which) {
			    	mainActivityView.getActivity().finish();
			        dialog.dismiss();
			    }
			
			});
			AlertDialog alert = builder.create();
			alert.show();
		}
	}
	
	/**
	 * Verfica que el usuario este conectado a internet
	 * @return boolean
	 */
	public boolean isOnline() {
	    ConnectivityManager connectivityManager = (ConnectivityManager) mainActivityView.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
	    return (netInfo != null && netInfo.isConnectedOrConnecting());
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		if(requestCode == REQUEST_EDITOR && resultCode == Activity.RESULT_OK) {
			mainActivityView.updatePostList(database.getPosts());
		}
		
		if(requestCode == REQUEST_AUTHORIZATION && resultCode == Activity.RESULT_CANCELED) {
			launchWebActivity(Blog.getAuthorizeEndpoint());
		}
		
		if(requestCode == REQUEST_AUTHORIZATION && resultCode == Activity.RESULT_OK) {
			blog.setCode(data.getExtras().getString("code"));
			AsyncHttpPost client = new AsyncHttpPost(new TokenTaskListener());
			client.putValues(blog.getTokenEndpointParameters());
			client.execute(new String[] {Blog.TOKEN_ENDPOINT});
		}
	}
	
	/**
	 * Eventos OnClick
	 * @param item
	 * @return boolean
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {
		
	        case R.id.menu_new_post:
	        	/* Lanzar el editor. */
	        	Intent intent = new Intent(mainActivityView.getActivity(), Editor.class);
	        	intent.putExtra("post_id", NEW_POST);
	        	intent.putExtra("blog_id", blog.getId());
	        	mainActivityView.getActivity().startActivityForResult(intent, REQUEST_EDITOR);
	        	break;
	        	
	        case R.id.menu_synchronize:
	        	syncPostList();
	        	break;
	        	
	        case R.id.menu_facebook:
	        	Intent fb_activity = new Intent(mainActivityView.getActivity(), LoginActivity.class);
	        	mainActivityView.getActivity().startActivity(fb_activity);
	        	break;
	    }
	    
	    return true;
	}
	
	/**
	 * Lanzar WebActivity para autenticaci�n
	 * @param url
	 */
	private void launchWebActivity(String url) {
		Intent intent = new Intent(mainActivityView.getActivity(), WebActivity.class);
		intent.putExtra("url", url);
		mainActivityView.getActivity().startActivityForResult(intent, REQUEST_AUTHORIZATION);
	}
	
	/**
	 * Sincroniza las entradas del blog, actualiza la vista
	 */
	public void syncPostList() {
		AsyncHttpGet get = new AsyncHttpGet(new SyncPostListListener());
		get.putHeader("Authorization", "Bearer " + blog.getToken());
		get.putValue("type", "post");
		get.putValue("status", "any");
		get.execute(new String[] {Blog.REST_URL + "/sites/" + String.valueOf(blog.getId()) + "/posts"});
	}

	public void onPause() {
		mainActivityView.dismissProgressDialog();
	}
	
	/**
	 * 
	 * @author Ignacio Javier Kovacs
	 *
	 */
	private class SyncPostListListener implements AsyncTaskListener {

		@Override
		public void onPreExecute() {
			mainActivityView.showProgressDialog();
		}

		@Override
		public void onPostExecute(String result) {
			try {			
				JSONObject jPost= new JSONObject(result);			
				JSONArray postArray = jPost.getJSONArray("posts");
				
				for(int i = 0; i < postArray.length(); i++) {
					
					/* Obtener post */
					jPost = postArray.getJSONObject(i);
					
					/* Obtener post y actualizarlo, o insertarlo */
					Post post = JSONParser.getPost(jPost);
					post.setBlogId(blog.getId());
					
					/* Buscar post en la base de datos. */
					Post old = database.getPost(post.getId());
					
					if(old != null) {
						if(old.getRawModified().before(post.getRawModified())) {
							database.update(post);
						}
					}
					else {
						database.insert(post);
					}
				}
				
			}
			catch (JSONException e) {
				Log.e("[JSONException]", e.getMessage());
			}
			
			/* Actualizar lista */
			mainActivityView.updatePostList(database.getPosts());
			mainActivityView.hideProgressDialog();
		}
		
	}
	
	/**
	 * 
	 * @author Ignacio Javier Kovacs
	 *
	 */
	private class TokenTaskListener implements AsyncTaskListener {

		@Override
		public void onPreExecute() {
			mainActivityView.showProgressDialog();
		}

		@Override
		public void onPostExecute(String result) {
			
			try {
				JSONObject object = new JSONObject(result);
				blog.setId(Integer.valueOf(object.getString("blog_id")));
				blog.setUrl(object.getString("blog_url"));
				blog.setToken(object.getString("access_token"));
				blog.setTokenType(object.getString("token_type"));
			}
			catch(JSONException e) {
				Log.e("[JSONException]", e.getMessage());
			}
			
			Log.i("[blog_code]", blog.getCode());
			Log.i("[blog_id]", String.valueOf(blog.getId()));
			Log.i("[blog_url]", blog.getUrl());
			Log.i("[blog_token]", blog.getToken());
			Log.i("[blog_token_type]", blog.getTokenType());
			
			
			/* Eleminar blog anterior, insertar nuevo */
			database.emptyTables();
			database.insert(blog);
			
			/* Sincronizar posts. */
			syncPostList();
			
			mainActivityView.showProgressDialog();
		}
	}
}
